<?php
namespace api\modules\v1\models\shop;

use api\modules\common\models\User;
use api\modules\v1\models\Common;
use api\modules\v1\models\shop\GoodsDetail;
use common\models\Functions;
use yii\base\Exception;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class Cart extends \common\models\shop\Cart
{

    public function getCartList(){
        try {
            $userInfo = (new User())->checkUser();
            $where['user_id'] = $userInfo['id'];

            $query = new Cart();
            $list = $query::getObjectByWhere($where)->with(['detail','detail.goods','detail.banner'])->asArray()->all();
            $result = [];
            foreach ($list as $k => $v) {
                $detailInfo =  ArrayHelper::getValue($v,'detail',[]);
                $goodsInfo = ArrayHelper::getValue($detailInfo,'goods',[]);
                $banners = ArrayHelper::getValue($detailInfo,'banner',[]);
                $tmp = [
                    'id' => $v['id'],
                    'goods_id' => $goodsInfo['id'],
                    'detail_id' => $detailInfo['id'],
                    'goods_name' => $goodsInfo['name'],
                    'spec_name' => $detailInfo['goods_spec'],
                    'price' => $detailInfo['goods_price'],
                    'num' => (int) $v['buy_num'],
                    'image' => $banners && $banners[0] ? $this->imageHost.$banners[0]['goods_image'] : '',
                ];

                $result[] = $tmp;
            }

            return Functions::formatRestAPI(0, '', $result);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 加入购物车
     * @return array
     */
    public function addCart() {
        try {
            $userInfo = (new User())->checkUser();
            $post = Yii::$app->request->post();
            $detailId = (int) $post['detail_id'];

            if (empty($detailId)) {
                throw new Exception('未知商品信息');
            }
            $detailInfo = GoodsDetail::getOneInfoById($post['detail_id']);

            $insert['user_id'] = $userInfo['id'];
            $insert['goods_id'] = $detailInfo['goods_id'];
            $insert['goods_detail_id'] = $detailId;

            $num = (int) $post['buy_num'];
            if (empty($num)) {
                throw new Exception('未知信息1');
            }

            //判断同类型的商品是否存在于购物车
            $checkInfo = static::getOneByWhere($insert);
            if (empty($checkInfo)) {
                if (empty($post['id'])) {
                    $insert['create_time'] = date("Y-m-d H:i:s");
                    $insert['buy_num'] = $num;
                    $res = static::insertData($insert);
                    if ($res === false) {
                        throw new Exception('系统错误');
                    }
                } else {
                    $currInfo = static::getOneInfoById($post['id']);

                    if (empty($currInfo) || $currInfo['user_id'] != $userInfo['id']) {
                        throw new Exception('未知信息2');
                    }

                    $insert['buy_num'] = $num;
                    $res = static::updateData($insert, ['id' => $post['id']]);
                    if ($res === false) {
                        throw new Exception('系统错误');
                    }
                }

            } else {
                if (empty($post['id'])) {
                    $num = $checkInfo['buy_num'] + $num;
                }
                $res = self::updateData(['buy_num' => $num], ['id' => $checkInfo['id']]);
                if ($res === false) {
                    throw new Exception('系统错误');
                }
            }

            return Functions::formatRestAPI(0, '成功加入购物车');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 修改购物车
     * @return array
     */
    public function modifyCart() {
        try {
            $userInfo = (new User())->checkUser();
            $post = Yii::$app->request->post();
            $id = (int) $post['id'];
            if (empty($id)) {
                throw new Exception('未知商品信息');
            }

            $detailInfo = GoodsDetail::getOneInfoById($post['detail_id']);

            $insert['goods_id'] = $detailInfo['goods_id'];
            $insert['goods_detail_id'] = $post['detail_id'];
            $insert['buy_num'] = (int) $post['buy_num'];

            $info = static::getOneInfoById($id);

            if (empty($info) || $info['user_id'] != $userInfo['id']) {
                throw new Exception('未知购物车信息');
            }

            $res = static::updateData($insert, ['id' => $id]);

            if ($res === false) {
                throw new Exception('系统错误，请联系开发小哥哥~');
            }

            return Functions::formatRestAPI(0, '修改成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function deleteCart($id = 0) {
        try {
            $userInfo = (new User())->checkUser();
            $id = $id ? $id : Yii::$app->request->post('id');
            $id = (int) $id;
            if (empty($id)) {
                throw new Exception('未知商品信息');
            }

            $info = static::getOneInfoById($id);

            if (empty($info) || $info['user_id'] != $userInfo['id']) {
                throw new Exception('未知购物车信息');
            }

            $res = static::deleteAll(['id' => $id]);

            if ($res === false) {
                throw new Exception('系统错误，请联系开发小哥哥~');
            }

            return Functions::formatRestAPI(0, '删除成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }
}
